package com.alvin.springshiro.kafka;

import lombok.extern.log4j.Log4j2;
import org.apache.kafka.common.errors.TopicExistsException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.context.event.EventListener;

import java.util.List;
import java.util.concurrent.ExecutionException;

@Log4j2
//@Configuration
public class KafkaTopicConfig {

    private final KafkaAdminUtil kafkaAdminUtil;

    public KafkaTopicConfig(KafkaAdminUtil kafkaAdminUtil) {
        this.kafkaAdminUtil = kafkaAdminUtil;
    }

    @Value("${custome.kafka.tipic.list}")
    private List<String> topicList;


    @EventListener(ContextRefreshedEvent.class)
    public void ContextStarted(ContextRefreshedEvent event){
        log.info(event.toString());
        log.info("系统启动了");

        topicList.forEach(topic ->{
            try {
                kafkaAdminUtil.createTopic(topic);
                log.info(String.format("topic(%s)创建成功", topic));
            } catch (ExecutionException e) {
                if(e.getCause() instanceof TopicExistsException){
                    log.warn("topic(my-replicated-topic)已存在，无需创建");
                }else{
                    log.error("topic(my-replicated-topic)创建失败", e);
                }
            } catch (InterruptedException e) {
                log.error("topic(my-replicated-topic)创建失败", e);
            }
        });


    }
}
